package vip.kqsy.cloud.ai.sdk;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import vip.kqsy.cloud.ai.sdk.exception.AiException;
import vip.kqsy.cloud.ai.sdk.model.BaseReq;
import vip.kqsy.cloud.core.common.util.JsonUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
@Slf4j
public class GptService {

    private static final OkHttpClient client;
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private final String key;

    static {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.169", 7890));
        client = new OkHttpClient.Builder()
                .connectTimeout(50, TimeUnit.SECONDS)
                .readTimeout(55, TimeUnit.SECONDS)
                .proxy(proxy)
                .build();
    }

    public <R> R send(BaseReq<R> param) {

        if (BaseReq.GET.equals(param.method())) {
            Request request = new Request.Builder()
                    .url(param.url())
                    .addHeader("Authorization", String.format("%s %s", "Bearer", key))
                    .build();
            getR(param, request);
        }


        if (BaseReq.POST.equals(param.method())) {

            RequestBody body = RequestBody.create(JsonUtil.toJson(param), JSON);
            Request request = new Request.Builder()
                    .url(param.url())
                    .addHeader("Authorization", String.format("%s %s", "Bearer", key))
                    .post(body)
                    .build();
            return getR(param, request);
        }

        throw new AiException("暂不支持请求方法");

    }

    private <R> R getR(BaseReq<R> param, Request request) {
        log.info("gpt-请求参数：{}", param);
        try (Response response = client.newCall(request).execute()) {
            String json = response.body().string();
            log.info("gpt-响应参数：{}", json);
            return JsonUtil.from(json, param.classType());
        } catch (IOException e) {
            throw new AiException("网络IO异常", e);
        }
    }

}
